package com.leona.splashlibrary;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import com.leona.splashlibrary.utils.SplashUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Description:
 * Data：2018/12/18 0018-14:13
 * Author: xjlei
 */
public class SplashActivity extends Activity {

    private ImageView mIvSplash;
    private  Button mBtnCountTime ;

    private Disposable mDisposable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);

        mIvSplash = (ImageView) findViewById(R.id.iv_splash);
        mIvSplash.setImageResource(SplashUtils.getImages("splash_bg" + SplashUtils.getRandom(1, 2)));

        mBtnCountTime = (Button) findViewById(R.id.btn_count_time);
        mBtnCountTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump();
            }
        });

        countDown();
    }

    //清除RxJava并跳转页面
    public void jump() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        Intent intent = new Intent() ;
        ComponentName cn = new ComponentName("com.green.card", "com.green.card.MainActivity") ;
        intent.setComponent(cn) ;
        startActivity(intent);
        finish();
    }

    private void countDown() {
        mDisposable = Observable.interval(0L, 1L, TimeUnit.SECONDS, AndroidSchedulers
                .mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        long offset = 5 - aLong;
                        if (offset < 0) {
                            jump();
                        } else {
                            mBtnCountTime.setText(getString(R.string.jupm, String.valueOf(offset)));
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

}
